package br.com.foxline.atlasmobile.novocadastro;

import java.util.ArrayList;
import java.util.List;

import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import br.com.foxline.atlasmobile.R;
import br.com.foxline.atlasmobile.dao.ProprietarioDao;
import br.com.foxline.atlasmobile.entities.Imovel;
import br.com.foxline.atlasmobile.entities.Proprietario;
import br.com.foxline.atlasmobile.util.UtilConnection;

public class CidadaoActivity extends Fragment {

	private Context context;
	private View view;

	private Imovel imovel;
	private ProprietarioDao proprietarioDao;

	private List<Proprietario> proprietarios;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		View rootView = inflater.inflate(R.layout.activity_cidadao, container,
				false);

		setHasOptionsMenu(true);
		
		proprietarios = new ArrayList<Proprietario>();

		view = rootView;
		context = container.getContext();
		imovel = ((CriarImovelActivity) getActivity()).getImovel();
		loadDao();

		ListView list = (ListView) rootView.findViewById(R.id.list_cidadao);

		CidadaoArrayAdapter arrayAdapter = new CidadaoArrayAdapter(context,
				R.layout.proprietario_item, proprietarios);
		list.setAdapter(arrayAdapter);

		return rootView;
	}

	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {

		menu.findItem(R.id.add_proprietario).setVisible(true);

		super.onCreateOptionsMenu(menu, inflater);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		switch (item.getItemId()) {
		case R.id.add_proprietario:
			Intent intent = new Intent(context,
					AddCidadaoActivity.class);
			intent.putExtra(UtilConnection.IMOVEL, imovel);
			startActivity(intent);
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
		
	}

	private void loadDao() {
		proprietarioDao = new ProprietarioDao(context);

	}

	private class CidadaoArrayAdapter extends ArrayAdapter<Proprietario> {

		private List<Proprietario> list;

		public CidadaoArrayAdapter(Context context, int textViewResourceId,
				List<Proprietario> objects) {
			super(context, textViewResourceId, objects);

			if (objects == null)
				list = new ArrayList<Proprietario>();
			list = objects;

		}

		@Override
		public int getCount() {
			return list.size();
		}

		@Override
		public Proprietario getItem(int position) {
			return list.get(position);
		}

		@Override
		public long getItemId(int position) {
			return super.getItemId(position);
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			return super.getView(position, convertView, parent);
		}
	}
}
